<template>
  <div class="fillcontain">
    <div class="user-header-title">
      <div class="left souIpt" ref="search" :model="search">
        <div class="table_container">
          <div class="table_container_header">
            <div class="table_container_header_left">
              <span class="user-header-title-lable">姓名:</span>
              <el-input size="small" v-model="search.take_name" placeholder="不限"></el-input>
              <span class="user-header-title-lable">手机号:</span>
              <el-input size="small" v-model="search.take_phone" placeholder="不限"></el-input>
              <span class="user-header-title-lable">状态:</span>
              <el-select v-model="search.o_status" clearable size="small" placeholder="不限">
                <el-option
                  v-for="(item,index) in {}"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-button
                size="small"
                class="filter-button"
                icon="el-icon-search"
                type="primary"
                @click="searchList"
              >查询</el-button>
              <el-button @click="addUserOnClick" type="primary" size="mini">添加</el-button>
              <el-button type="success" icon="el-icon-refresh" size="mini" @click="refresh">刷新</el-button>
            </div>
            <div class="table_container_header_right"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="table_container">
      <el-table
        v-loading="showLoading"
        @selection-change="getRowDatas"
        :row-class-name="tableRowClassName"
        :data="tableData"
        style="width:100%"
        height="600"
      >
        <el-table-column type="index" label="序号"  width="50"></el-table-column>
        <el-table-column label="员工真实姓名" prop="UserName"  width="110"></el-table-column>
        <el-table-column label="登录用户名" prop="LoginName"  width="110"></el-table-column>
        <el-table-column label="手机号" prop="Mobile"  width="110"></el-table-column>
        <el-table-column label="是否绑定手机" prop="HasMobile"  width="110"></el-table-column>
        <el-table-column label="机构" prop="OrgID"  width="110"></el-table-column>
        <el-table-column label="所属部门" prop="DepartmentID"  width="80">
          <template slot-scope="scope">{{getDicMsgById('DepartmentType',scope.row.DepartmentID)}}</template>
        </el-table-column>
        <el-table-column label="状态" width="75" prop="Status" >
          <template slot-scope="scope">{{getDicMsgById('RegistStatus',scope.row.Status)}}</template>
        </el-table-column>
        <el-table-column label="用户来源类型" width="110" prop="UserSourceTypeID" ></el-table-column>
        <el-table-column label="登录注册时间" prop="RegisterTime"  width="160"></el-table-column>
        <el-table-column label="查询代码" prop="SearchCode"  width="100"></el-table-column>
        <el-table-column label="员工类型" prop="UserType"  width="100"></el-table-column>
        <el-table-column label="操作"  fixed="right" min-width="250">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="allocationJurisdiction(scope.$index, scope.row)"
                type="success"
                size="mini"
              >分配权限</el-button>
              <el-button
                type="primary"
                @click="updataUserData(scope.$index, scope.row)"
                size="mini"
              >编辑</el-button>
              <el-button
                @click="deletRoleData(scope.$index, scope.row)"
                type="danger"
                size="mini"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :title="editTitle" :visible.sync="addUserDialogStatus">
        <el-form :model="userSubObj" label-width="80px">
          <el-form-item label="登录名:">
            <el-input autofocus v-model="userSubObj.LoginName" placeholder="登录名"></el-input>
          </el-form-item>
          <el-form-item label="姓名:">
            <el-input autofocus v-model="userSubObj.UserName" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="机构">
            <el-select v-model="userSubObj.OrgID" placeholder="请选择">
              <el-option
                v-for="(item,index) in orgData"
                :key="index"
                :label="item.Name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="备注:" prop="certNo">
              <el-input type="textarea" autofocus v-model="userSubObj.Note" placeholder="请输入备注"></el-input>
          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogStatus = false">取 消</el-button>
          <el-button type="primary" @click.native="addUserSubClick">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="分配权限" :visible.sync="authorityDistribution">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="组" name="first">
            <el-form :model="selectTable">
              <el-tree
                ref="groupsTreeDataRef"
                @check="groupsCurrentChecked"
                :data="groupsTreeData"
                show-checkbox
                node-key="id"
                :default-expanded-keys="[0]"
                :default-checked-keys="defaultGroupsTreeData"
              ></el-tree>
              <el-button type="primary" @click="updateRole('groups')">确定</el-button>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="角色" name="second">
            <el-form :model="selectTable">
              <el-tree
                ref="roleTreeDataRef"
                @check="roleCurrentChecked"
                :data="roleTreeData"
                show-checkbox
                node-key="id"
                :default-expanded-keys="[0]"
                :default-checked-keys="defaultRoleTreeData"
              ></el-tree>
              <el-button type="primary" @click="updateRole('role')">确定</el-button>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="操作权限" name="third">
            <el-form :model="selectTable">
              <el-tree
                ref="operationTreeDataRef"
                @check="operationCurrentChecked"
                :data="operationTreeData"
                show-checkbox
                node-key="id"
                :default-expanded-keys="[0]"
                :default-checked-keys="defaultOperationTreeData"
              ></el-tree>
              <el-button type="primary" @click="updateRole('operation')">确定</el-button>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="可访问的机构" name="fourth">
            <el-form :model="selectTable">
              <el-tree
                ref="orgTreeDataRef"
                @check="orgCurrentChecked"
                :data="orgTreeData"
                show-checkbox
                node-key="id"
                :default-expanded-keys="[0]"
                :default-checked-keys="defaultOrgTreeData"
              ></el-tree>
              <el-button type="primary" @click="updateRole('org')">确定</el-button>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button @click="authorityDistribution = false">取 消</el-button>
        </div>
      </el-dialog>

      <div class="paginationWrap right">
        <el-pagination
          v-if="pagination.paginationShow"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pagination.currentPage"
          :page-sizes="pagination.sizes"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.count"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { get, post } from "../../common/apiconfig";
import { getDicMsgById } from "../../common/common";
export default {
  data() {
    return {
      dialogStatus: 0,
      activeName: "",
      tableData: [],
      authorityDistribution: false,
      addUserDialogStatus: false,
      orgData: [],
      editTitle: "添加用户",
      sourceOperationTreeData: [],
      groupsTreeData: [],
      roleTreeData: [],
      operationTreeData: [],
      orgTreeData: [],

      defaultGroupsTreeData: [],
      defaultRoleTreeData: [],
      defaultOperationTreeData: [],
      defaultOrgTreeData: [],

      groupsDetailList: [],
      roleDetailList: [],
      operationDetailList: [],
      orgDetailList: [],

      selectedCategory: [],
      address: {},
      fileList: [],
      xiangQing: {},
      search: {},
      userSubObj: {},
      rules: {},
      showLoading: false,
      pagination: {
        count: 0,
        size: 10,
        currentPage: 1,
        paginationShow: true
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      selectTable: {}
    };
  },
  created() {},
  watch: {},
  components: {},
  computed: {},
  mounted() {
    this.getList();
    this.getOrgList();
    this.getGroupsList();
    this.getRoleList();
    this.getOperationList();
    console.log(JSON.parse(localStorage.getItem("dictionariesData")));
    console.log(getDicMsgById("OutStorageType", 4));
  },
  methods: {
    getDicMsgById(type, id) {
      return getDicMsgById(type, id);
    },
    getList() {
      let that = this;
      let { currentPage: page, size: rows } = that.pagination;
      get("/UserList", {
        page,
        rows
      }).then(d => {
        if (d.code == "001") {
          that.tableData = d.rows;
          that.pagination.count = d.records;
        } else {
          console.log(d.msg);
        }
      });
    },
    getOrgList() {
      let that = this;
      get("/GetTreeList", {
        TreeType: "Org"
      }).then(d => {
        if (d.code == "001") {
          that.orgData = d.data.items;
          that.orgTreeData = that.renderTreeData(d.data.items);
        } else {
          console.log(d.msg);
        }
      });
    },
    getGroupsList() {
      let that = this;
      get("/GetTreeList", {
        TreeType: "Groups"
      }).then(d => {
        if (d.code == "001") {
          that.groupsTreeData = that.renderTreeData(d.data.items);
        }
      });
    },
    getRoleList() {
      let that = this;
      get("/GetTreeList", {
        TreeType: "Role"
      }).then(d => {
        if (d.code == "001") {
          that.roleTreeData = that.renderTreeData(d.data.items);
        }
      });
    },
    getOperationList() {
      let that = this;
      get("/GetTreeList", {
        TreeType: "Operation"
      }).then(d => {
        if (d.code == "001") {
          that.sourceOperationTreeData = d.data.items;
          that.operationTreeData = that.renderTreeData(d.data.items);
        }
      });
    },
    addUserOnClick() {
      this.userSubObj = {};
      this.dialogStatus = 0;
      this.editTitle = "添加用户";
      this.addUserDialogStatus = true;
    },
    addUserSubClick() {
      let that = this;
      let { LoginName, UserName, OrgID, ID } = that.userSubObj;
      let url = "/UserNew";
      let errMsg = "添加出错";
      let obj = {
        LoginName,
        UserName,
        OrgID
      };
      if (this.dialogStatus != 0) {
        errMsg = "修改出错";
        obj.ID = ID;
        url = "/UserUpdate";
      }
      post(url, obj).then(d => {
        if (d.code == "001") {
          that.dialogStatus = 0;
          that.addUserDialogStatus = false;
          that.$message.success("操作成功");
          that.getList();
        } else {
          that.$message.error(errMsg);
        }
      });
    },
    updataUserData(index, item) {
      this.editTitle = "修改用户";
      this.dialogStatus = 1;
      this.addUserDialogStatus = true;
      this.userSubObj = item;
    },
    handleSizeChange(val) {
      this.pagination.size = val;
      this.getList();
    },
    handleCurrentChange() {
      this.getList();
    },
    allocationJurisdiction(index, row) {
      let that = this;
      let { ID } = row;

      this.authorityDistribution = true;
      this.activeItem = row;

      this.$nextTick(() => {
        that.$refs.groupsTreeDataRef.setCheckedKeys([]);
        that.$refs.roleTreeDataRef.setCheckedKeys([]);
        that.$refs.operationTreeDataRef.setCheckedKeys([]);
        that.$refs.orgTreeDataRef.setCheckedKeys([]);
      });
      let p1 = that.getPromiseRquert(
        "/UserGroupsList",
        ID
      );
      let p2 = that.getPromiseRquert(
        "/UserRoleList",
        ID
      );
      let p3 = that.getPromiseRquert(
        "/UserOperationList",
        ID
      );
      let p4 = that.getPromiseRquert(
        "/UserOrgList",
        ID
      );
      Promise.all([p1, p2, p3, p4])
        .then(result => {
          console.log(result);
          that.defaultGroupsTreeData = result[0];
          that.defaultRoleTreeData = result[1];
          that.defaultOperationTreeData = result[2];
          that.defaultOrgTreeData = result[3];

          that.groupsDetailList = result[0];
          that.roleDetailList = result[1];
          that.operationDetailList = result[2];
          that.orgDetailList = result[3];
        })
        .catch(err => {
          console.log(err);
        });
    },
    getPromiseRquert(url, UserID) {
      return new Promise((resolve, reject) => {
        get(url, {
          UserID
        }).then(d => {
          if (d.code == "001") {
            if (d.rows[0] == 0) {
              d.rows.shift();
            }
            resolve(d.rows);
          } else {
            reject("err");
          }
        });
      });
    },
    updateRole(type) {
      let that = this;
      let { ID: UserID } = this.activeItem;
      let obj = {
        groups: {
          url: "/UserGroupsUpdate",
          DetailList: this.groupsDetailList
        },
        role: {
          url: "/UserRoleUpdate",
          DetailList: this.roleDetailList
        },
        operation: {
          url: "/UserOperationUpdate",
          DetailList: this.operationDetailList
        },
        org: {
          url: "/UserOrgUpdate",
          DetailList: this.orgDetailList
        }
      };
      let param = {
        UserID,
        DetailList: obj[type].DetailList.join()
      };
      if (type == "operation") {
        param.DetailListAdd = param.DetailList;
        param.DetailListDec = that.getDetailListDecData(param.DetailList);
      }
      post(obj[type].url, param).then(d => {
        if (d.code == "001") {
          that.$message.success("修改成功");
        } else {
          that.$message.success("修改失败");
        }
      });
    },
    getDetailListDecData(DetailList) {
      console.log(DetailList);
      let arr = this.sourceOperationTreeData.filter(item => {
        return !DetailList.split(",").includes(item.ID + "");
      });
      arr.shift();
      return arr
        .map(item => {
          return item.ID;
        })
        .join();
    },
    deletRoleData(index, item) {
      let that = this;
      let { ID } = item;
      this.$confirm("确定要删除该条记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          post("/UserDelete", {
            ID
          }).then(d => {
            if (d.code == "001") {
              that.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            } else {
              that.$message.error("删除出错！");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    searchList() {},
    getRowDatas(row) {
      console.log(row);
    },
    getCreatFormData() {},
    refresh() {
      this.getList();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row);
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    renderTreeData(data) {
      data.forEach(item => {
        item.id = item.ID;
        item.label = item.Name;
      });
      let firstItem = data.filter(item => {
        return item.ID == 0;
      })[0];
      firstItem.children = this.getItemChilren(firstItem.ID, data);
      firstItem.children.forEach(element => {
        element.children = this.getItemChilren(element.ID, data);
      });
      firstItem.children.forEach(element => {
        element.children.forEach(item => {
          item.children = this.getItemChilren(item.ID, data);
        });
      });
      return [firstItem];
    },
    getItemChilren(ID, data) {
      return data.filter(item => {
        return item.ParentID == ID;
      });
    },
    groupsCurrentChecked(nodeObj, SelectedObj) {
      this.groupsDetailList = SelectedObj.checkedKeys;
    },
    roleCurrentChecked(nodeObj, SelectedObj) {
      this.roleDetailList = SelectedObj.checkedKeys;
    },
    operationCurrentChecked(nodeObj, SelectedObj, a, b) {
      console.log(nodeObj);
      console.log(SelectedObj);
      console.log(a);
      console.log(b);
      this.operationDetailList = SelectedObj.checkedKeys;
    },
    orgCurrentChecked(nodeObj, SelectedObj) {
      this.orgDetailList = SelectedObj.checkedKeys;
    }
  },
  destroyed() {}
};
</script>

<style scoped >
.table_container {
  padding: 20px;
  max-width: 100vw;
  overflow: auto;
}

.user-header-title {
  overflow: hidden;
  padding-left: 20px;
}

.user-header-title-lable {
  font-size: 14px;
  margin: 0 15px;
  font-weight: 600;
}

.filter-button {
  margin-left: 10px;
}

.souIpt .el-input {
  width: 200px;
}

.fillcontain {
  border-radius: 8px;
  padding: 8px;
  background-color: #fff;
}

.table_container_header_left {
  float: left;
  margin-left: -20px;
}

.paginationWrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
